import 'dart:async';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/utils/adapt.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/validator.dart';
import 'package:star_author/views/login/login_page.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/checkbox.dart';
import 'package:star_author/widgets/dialog/dialog_type.dart';
import 'package:star_author/widgets/tap_transition_widget.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// import 'package:fluwx/fluwx.dart';
// import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';

import '../../widgets/dialog/sure_dialog.dart';

final int seconds = 60;

class PhoneLoginPage extends StatefulWidget {
  static String routeName = '/PhoneLoginPage';

  final bool isShowWeChat;
  final String jumpFrom;

  const PhoneLoginPage({
    Key? key,
    this.isShowWeChat = true,
    this.jumpFrom = '',
  }) : super(key: key);

  @override
  State<PhoneLoginPage> createState() => _PhoneLoginPageState();
}

class _PhoneLoginPageState extends State<PhoneLoginPage> {
  bool isChecked = false;
  bool availableBtn = false;
  bool waiting = false;

  int _start = seconds;
  Timer? _timer;
  final _mobileController = TextEditingController();
  final _codeController = TextEditingController();
  final _mobileNode = new FocusNode();
  final _codeNode = new FocusNode();

  GlobalKey _formKey = new GlobalKey<FormState>();

  void startStopWatch() {
    _timer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_start > 0) {
        setState(() {
          availableBtn = false;
          _start--;
        });
      } else {
        timer.cancel();
        setState(() {
          availableBtn = true;
          _start = seconds;
        });
      }
    });
  }

  bool get isTimeActive {
    return ![false, null].contains(_timer?.isActive);
  }

  get canFetchCode {
    return !isTimeActive && availableBtn && !waiting;
  }

  get messageButtonTextColor {
    return canFetchCode ? Color(0xFF198CFF) : ColorConf.highlightGray;
  }

  bool beforeLoginChecking() {
    if (!isChecked) {
      CustomToast.show("登录前请先勾选条款");
      return false;
    }
    return true;
  }

  void getMessageCode() async {
    if (!canFetchCode) return;

    setState(() {
      waiting = true;
    });
    final mobile = _mobileController.text;
    try {
      HttpUtil.commonRequest(
        Get.context!,
        '/api/v1/message_code',
        method: HttpUtil.MethodPost,
        isErrorToast: false,
        isLoading: false,
        data: {
          'mobile': mobile,
        },
      ).then((value) {
        CustomToast.show('发送成功');
        startStopWatch();
      }).catchError((e) {
        DioError dioError = e as DioError;
        String msg = dioError.response?.data['msg'] ?? "";
        DialogUtil.showMyDialog(
            dialogType: DialogType.phone_message_day_restrict,
            param: {
              "tips": msg,
            },
            rightButtonOnTap: () {});
      });
    } finally {
      setState(() {
        waiting = false;
      });
    }
  }

  String get getMessageButtonText {
    if (isTimeActive) {
      return '重新发送${_start}s';
    } else {
      return '获取验证码';
    }
  }

  bool isValidCode(code) {
    if ([null, ''].contains(code)) return false;

    return code.toString().length >= 4;
  }

  // StreamSubscription<BaseWeChatResponse>? streamSubscription; //绑定

  @override
  void initState() {
    super.initState();
    _mobileController.addListener(() {
      final String text = _mobileController.text;
      setState(() {
        availableBtn = Validator.validMobile(text) == null;
      });
    });
    init();
  }

  bool isWeChatInstalled = false;

  init() async {
    // isWeChatInstalled = await fluwx.isWeChatInstalled; //苹果审核 没有安装app不能显示第三方登录
    //
    // setState(() {});
    //
    // streamSubscription = fluwx.weChatResponseEventHandler.listen((res) async {
    //   streamSubscription?.cancel();
    //   if (res is fluwx.WeChatAuthResponse) {
    //     String? code = res.code;
    //     if (code == null) {
    //       CustomToast.show("微信授权失败");
    //     } else {
    //       try {
    //         if (res.errCode == 0) {
    //           final response = await HttpUtil.commonRequest(
    //             context,
    //             ApiManager.sessions_wechat_app,
    //             method: HttpUtil.MethodPost,
    //             data: LoginPageHandler().getRequestMap({"code": code}),
    //             isErrorToast: false,
    //             isCatchErrorLogin: false,
    //             isLoading: true,
    //           );
    //
    //           if (response.statusCode == 201) {
    //             Get.back();
    //
    //             String token = response.data['token'];
    //
    //             UserUtil.setToken(context, token);
    //             UserUtil.tokenIsInvalid = true;
    //
    //             UserUtil.onLoginCallback(response.data,
    //                 jumpFrom: widget.jumpFrom);
    //           } else {
    //             CustomToast.show("登录失败");
    //           }
    //         }
    //       } catch (e) {
    //         CustomToast.show("登录失败");
    //       }
    //     }
    //   }
    // });
  }

  //切换环境
  updateAPIConfig() {
    // final mobile = _mobileController.text;
    // if (mobile == "huiliu@1234") {
    //   //如果是测试环境 切换到正式环境
    //   if (EnvConfig.isDev()) {
    //     EnvConfig.instance?.updateConfig(Env.PROD);
    //     App.miniProgramType = WXMiniProgramType.RELEASE;
    //   } else {
    //     EnvConfig.instance?.updateConfig(Env.DEV);
    //     App.miniProgramType = WXMiniProgramType.TEST;
    //   }
    //   String current_env = EnvConfig.instance?.getCurrentEnv();
    //   CustomToast.show("当前为$current_env,已自动退出版本登录，请重新登录");
    //   //保存当前是否是测试环境 true为是 false为不是
    //   SpUtil.putBool(EnvConfig.local_key, EnvConfig.isDev());
    //   GlobalEventBus().bus.fire(UserLoginEvent(false));
    //   final user = Provider.of<UserProvider>(context, listen: false);
    //   StatisticsUtil.logout();
    //   user.clearToken();
    //   RongUtil.disconnect();
    //
    //   ///断开ws
    //   LogUtil.v('WebSocketManage WebSocket连接关闭 - setting');
    //   WebSocketManage().closeSocket();
    //
    //   ///取消极光推送绑定
    //   JPush().deleteAlias();
    //   return;
    // }
  }

  void onLoginMobile() async {
    updateAPIConfig();
    if (!beforeLoginChecking()) {
      return;
    }

    final formState = _formKey.currentState as FormState;

    if (!formState.validate()) {
      return;
    }

    final code = _codeController.text;
    final mobile = _mobileController.text;

    var response = await HttpUtil.commonRequest(
      context,
      ApiManager.sessions_normal,
      method: HttpUtil.MethodPost,
      isErrorToast: false,
      isCatchErrorLogin: false,
      isLoading: true,
      data: LoginPageHandler().getRequestMap(
        {
          'mobile': mobile,
          'code': code,
        },
      ),
    ).catchError((e) {
      DioError dioError = e as DioError;
      CustomToast.show("${dioError.response?.data['msg'] ?? ""}");
    });

    Get.back();

    String token = response.data['token'];

    UserUtil.setToken(context, token);

    GlobalEventBus().bus.fire(UserLoginEvent(true));
  }

  @override
  void dispose() {
    _timer?.cancel();
    _mobileController.dispose();
    _codeController.dispose();
    _mobileNode.dispose();
    _codeNode.dispose();
    // streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: Colors.white,
          body: Stack(
            children: [
              Container(
                child: Image.asset(
                  RoucesUtil.getAssets('bg_anchor_lt'),
                ),
              ),
              Container(
                width: double.infinity,
                child: Text(
                  '欢迎使用',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 32.sp,
                    fontFamily: 'Alibaba PuHuiTi 3.0',
                    fontWeight: FontWeight.w900,
                  ),
                ),
                padding: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top + 40.w,
                  left: 20.w,
                ),
              ),
              Container(
                padding: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top + 40.w + 40.w,
                ),
                child: GestureDetector(
                  onTap: () {
                    FocusManager.instance.primaryFocus?.unfocus();
                  },
                  child: Container(
                    height: MediaQuery.of(context).size.height -
                        44.w -
                        Adapt.statusBarHeight -
                        Adapt.bottomHeight,
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.only(
                              top: 40.w + 40.w,
                              left: 20.w,
                              right: 20.w,
                            ),
                            color: Colors.white,
                            child: Form(
                              key: _formKey,
                              child: Column(
                                children: [
                                  Container(
                                    height: 62.w,
                                    decoration: BoxDecoration(
                                      color: Color(0xFFF6F6F6),
                                      borderRadius: BorderRadius.circular(50.w),
                                    ),
                                    alignment: Alignment.centerLeft,
                                    child: TextFormField(
                                      controller: _mobileController,
                                      autovalidateMode:
                                          AutovalidateMode.onUserInteraction,
                                      focusNode: _mobileNode,
                                      keyboardType: TextInputType.number,
                                      decoration: InputDecoration(
                                        enabledBorder: InputBorder.none,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Container(
                                          padding: EdgeInsets.symmetric(
                                            horizontal: 10.w,
                                          ),
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              SizedBox(
                                                width: 10.w,
                                              ),
                                              Text(
                                                '+86',
                                                style: TextStyle(
                                                  color: ColorConf.black,
                                                  fontSize: 18.sp,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                              SizedBox(
                                                width: 12.w,
                                              ),
                                              Container(
                                                width: 1.w,
                                                height: 24.w,
                                                decoration: BoxDecoration(
                                                    color: Color(0xFFD9D9D9)),
                                              )
                                            ],
                                          ),
                                        ),
                                        prefixIconConstraints: BoxConstraints(
                                          maxHeight: 24.sp,
                                        ),
                                        hintText: "请输入手机号码",
                                        hintStyle: TextStyle(
                                          color: ColorConf.highlightGray,
                                          fontSize: 16.sp,
                                        ),
                                      ),
                                      validator: (v) {
                                        if (_mobileNode.hasFocus) return null;
                                        return Validator.validMobile(v);
                                      },
                                      style: TextStyle(
                                        fontSize: 18.sp,
                                        color: Colors.black,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(
                                      top: 20.w,
                                    ),
                                    padding: EdgeInsets.only(
                                      left: 20.w,
                                      right: 20.w,
                                    ),
                                    height: 62.w,
                                    decoration: BoxDecoration(
                                      color: Color(0xFFF6F6F6),
                                      borderRadius: BorderRadius.circular(50.w),
                                    ),
                                    alignment: Alignment.centerLeft,
                                    child: TextFormField(
                                      keyboardType: TextInputType.number,
                                      controller: _codeController,
                                      autovalidateMode:
                                          AutovalidateMode.onUserInteraction,
                                      focusNode: _codeNode,
                                      inputFormatters: [
                                        LengthLimitingTextInputFormatter(4)
                                      ],
                                      decoration: InputDecoration(
                                        enabledBorder: InputBorder.none,
                                        focusedBorder: InputBorder.none,
                                        suffixIcon: Container(
                                          child: GestureDetector(
                                            child: Text(
                                              getMessageButtonText,
                                              style: TextStyle(
                                                color: messageButtonTextColor,
                                                fontSize: 16.sp,
                                              ),
                                            ),
                                            onTap: () {
                                              getMessageCode();
                                            },
                                          ),
                                        ),
                                        suffixIconConstraints: BoxConstraints(
                                          maxHeight: 24.w,
                                        ),
                                        hintText: "请输入验证码",
                                        hintStyle: TextStyle(
                                          color: ColorConf.highlightGray,
                                          fontSize: 16.sp,
                                        ),
                                        focusColor: ColorConf.red,
                                      ),
                                      validator: (v) {
                                        if (_codeNode.hasFocus) return null;
                                        if (!isValidCode(v)) return '验证码不合法';
                                      },
                                      style: TextStyle(
                                        fontSize: 18.sp,
                                        color: Colors.black,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 9.w),
                                    alignment: Alignment(-1.0, 0.0),
                                    child: Text(
                                      '未注册的手机号验证后自动创建回流账号',
                                      style: TextStyle(
                                        color: ColorConf.lightGray,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 40.w),
                                    width: double.infinity,
                                    child: ButtonWidget(
                                      enabled: isChecked,
                                      onPressed: () async {
                                        onLoginMobile();
                                      },
                                      type: ButtonType.bgGradientOrange,
                                      child: Text(
                                        '登录',
                                        style: TextStyle(
                                          fontSize: 16.sp,
                                          fontWeight: FontWeight.w500,
                                          color: ColorConf.black,
                                        ),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                          Column(
                            children: [
                              Container(
                                width: double.infinity,
                                child: Wrap(
                                  alignment: WrapAlignment.center,
                                  //沿主轴方向居中
                                  direction: Axis.horizontal,
                                  crossAxisAlignment: WrapCrossAlignment.center,
                                  children: [
                                    ClipRRect(
                                      child: CheckboxWidget(
                                        onChanged: (val) {
                                          setState(() {
                                            isChecked = val;
                                          });
                                        },
                                        select: isChecked,
                                      ),
                                      borderRadius: BorderRadius.circular(50.w),
                                    ),
                                    TapTransitionWidget(
                                      onPressed: () {
                                        setState(() {
                                          isChecked = !isChecked;
                                        });
                                      },
                                      child: Text(
                                        '我已阅读并同意',
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: ColorConf.lightGray,
                                        ),
                                      ),
                                    ),
                                    TapTransitionWidget(
                                      onPressed: () {},
                                      child: Text(
                                        '《用户协议》',
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: ColorConf.blue,
                                        ),
                                      ),
                                    ),
                                    TapTransitionWidget(
                                      onPressed: () {},
                                      child: Text(
                                        '《隐私条款》',
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: ColorConf.blue,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        onWillPop: () async {
          GlobalEventBus().bus.fire(UserLoginEvent(false));
          return Future.value(true);
        });
  }
}
